package com.icloud.cer.rest.web.filter;

import java.io.IOException;
import java.util.Date;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.icloud.cer.rest.common.ContextHolder;
import com.icloud.cer.rest.config.ServerConfigHolder;
import com.icloud.cer.rest.util.StringUtils;
import com.icloud.cer.rest.util.XMLUtils;
import com.icloud.cer.rest.web.bean.ArrayTime;
import com.icloud.cer.rest.web.bean.Visitor;

public class IPFilter implements Filter {
	private Log log=LogFactory.getLog(IPFilter.class);
	
	private final String VISITOR_KEY = "VISITOR_KEY";
	private final String REFRESH_INTERVAL = "refresh.interval";
	private final String REFRESH_COUNT = "refresh.count";
	
	private int  refreshInterVal = 10;
	private int  refreshCount = 10;
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ServletContext sct = filterConfig.getServletContext();
		String interVal = sct.getInitParameter(REFRESH_INTERVAL);
		String count = sct.getInitParameter(REFRESH_COUNT);
		log.info("refresh.interval = " + interVal);
		log.info("refresh.count = " + count);
		if(StringUtils.isNotEmpty(interVal)) {
			try {
				refreshInterVal = Integer.parseInt(interVal);
			} catch (Exception e) {
				log.error("parse parameter:refresh.interval error.use 10 as default");
			}
		}
		
		if(StringUtils.isNotEmpty(count)) {
			try {
				refreshCount = Integer.parseInt(count);
			} catch (Exception e) {
				log.error("parse parameter:refresh.count error.use 10 as default");
			}
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		HttpSession session = ((HttpServletRequest)request).getSession();
		String sessionID = session.getId();//会话ID 
		log.debug("sessionId:" + sessionID);
		if(req.getRequestURI().contains("error.htm")) {
			try {
				chain.doFilter(request, response);
			} finally {
				ContextHolder.requestClear();
			}
			return;
		}
		Date now =new Date();
		long current = now.getTime();
		Visitor visitor = (Visitor)session.getAttribute(VISITOR_KEY);
		//第一次请求
		if(visitor == null) {
			ArrayTime timeQueue = new ArrayTime(refreshCount);
			timeQueue.setLength(refreshCount);
			timeQueue.insert(current);
			
			visitor = new Visitor();
			visitor.setSessionID(sessionID);
			visitor.setRequestTimeQueue(timeQueue);
			session.setAttribute(VISITOR_KEY, visitor);
			try {
				chain.doFilter(request, response);
			} finally {
				ContextHolder.requestClear();
			}
			return;
		}
		//第N次请求(N>1)
		ArrayTime timeQueue = visitor.getRequestTimeQueue();
		timeQueue.insert(current);
		long span =  timeQueue.getLast() - timeQueue.getFirst();
		log.info("last:" + timeQueue.getLast());
		log.info("first:" + timeQueue.getFirst());
		log.info("==>>" + span);
		if(span < refreshInterVal * 1000 && timeQueue.getLast() != 0) {
			log.warn("");
			//将该用户加入黑名单 
			String blackIpConfig = session.getServletContext().getInitParameter("blackIpConfig");
			String ip = request.getRemoteAddr();
			XMLUtils.addBlackIp(blackIpConfig, ip);
			log.warn("refresh black ip list.");
			ServerConfigHolder.getInstance().refreshBlackIpList(blackIpConfig);
			res.sendRedirect(req.getContextPath() + "/error.htm?errmsg=morerequest");
			return;
		}
		
		try {
			chain.doFilter(request, response);
		} finally {
			ContextHolder.requestClear();
		}
	}

	@Override
	public void destroy() {
	}

}
